package org.kzwl.service.web.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.ResponseData;
import org.kzwl.comm.pojo.bo.AdminQueryCuVolunteersBO;
import org.kzwl.comm.pojo.bo.SaveCuVolunteersBO;
import org.kzwl.comm.pojo.bo.thear.GetRecordBO;
import org.kzwl.comm.pojo.bo.volunteers.RegisterVolunteersBO;
import org.kzwl.comm.pojo.bo.volunteers.VolunteersBasicBO;
import org.kzwl.comm.pojo.bo.volunteers.VolunteersSignBO;
import org.kzwl.comm.pojo.dto.volunteers.QueryDetailsDTO;
import org.kzwl.comm.pojo.dto.volunteers.VolunteersDTO;
import org.kzwl.entity.app.CuVolunteersUser;
import org.kzwl.entity.app.User;
import org.kzwl.entity.app.Verification;
import org.kzwl.entity.web.CuVenuesCategory;
import org.kzwl.entity.web.CuVolunteers;
import org.kzwl.entity.web.CuVolunteersCategory;
import org.kzwl.entity.web.CuVolunteersSign;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.mapper.web.*;
import org.kzwl.service.app.VerificationService;
import org.kzwl.service.web.CuVolunteersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-12-17
 */
@Service
public class CuVolunteersServiceImpl extends ServiceImpl<CuVolunteersMapper, CuVolunteers> implements CuVolunteersService {

    @Autowired
    private CuVolunteersMapper volunteersMapper;

    @Autowired
    private CuVenuesCategoryMapper categoryMapper;

    @Autowired
    private CuVolunteersCategoryMapper volunteersCategoryMapper;

    @Autowired
    private CuVolunteersUserMapper volunteersUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CuVolunteersSignMapper signMapper;

    @Autowired
    private VerificationService verificationService;

    @Override
    public ResponseData<Void> saveOne(SaveCuVolunteersBO saveCuVolunteersBO) {
        String s = RandomUtil.randomNumbers(6);

        CuVolunteers cuVolunteers = new CuVolunteers();
        BeanUtils.copyProperties(saveCuVolunteersBO, cuVolunteers);
        cuVolunteers.setCuVolunteersNumber(s);
        this.baseMapper.insert(cuVolunteers);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<IPage<CuVolunteers>> queryPage(AdminQueryCuVolunteersBO adminQueryCuVolunteersBO) {
        QueryWrapper<CuVolunteers> cuVolunteersQueryWrapper = new QueryWrapper<>();
        cuVolunteersQueryWrapper
                .lambda()
                .apply(adminQueryCuVolunteersBO.getCuVolunteersStartDate() != null, "date_format (cu_volunteers_end_date,'%Y-%m-%d') >= date_format('" + adminQueryCuVolunteersBO.getCuVolunteersStartDate() + "','%Y-%m-%d')")
                .apply(adminQueryCuVolunteersBO.getCuVolunteersEndDate() != null, "date_format (cu_volunteers_end_date,'%Y-%m-%d') <= date_format('" + adminQueryCuVolunteersBO.getCuVolunteersEndDate() + "','%Y-%m-%d')");

        Page<CuVolunteers> cuVolunteersPage = this.baseMapper.selectPage(new Page<>(adminQueryCuVolunteersBO.getCurrent(), adminQueryCuVolunteersBO.getSize()), cuVolunteersQueryWrapper);

        return new ResponseData<>(cuVolunteersPage);
    }

    @Override
    public ResponseData<Void> updateOne(SaveCuVolunteersBO saveCuVolunteersBO) {
        CuVolunteers cuVolunteers = new CuVolunteers();
        BeanUtils.copyProperties(saveCuVolunteersBO, cuVolunteers);
        this.baseMapper.updateById(cuVolunteers);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<Void> deleteId(Long Id) {

        CuVolunteers cuVolunteers = this.baseMapper.selectById(Id);
        if (ObjectUtil.isNull(cuVolunteers)) {
            throw new BizException("找不到此信息");
        } else if (cuVolunteers.getCuVolunteersServiceCount() > 0) {
            throw new BizException("此志愿服务已经有人报名,无法删除");
        }
        this.baseMapper.deleteById(Id);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<CuVolunteers> queryId(Long Id) {
        if (ObjectUtil.isNull(this.baseMapper.selectById(Id))) {
            throw new BizException("找不到此信息");
        }
        return new ResponseData<>(this.baseMapper.selectById(Id));
    }

    //region 志愿者服务基础查询
    @Override
    public IPage<VolunteersDTO> queryBasic(VolunteersBasicBO bo) {
        IPage<CuVolunteers> page = new Page<>();
        page.setCurrent(bo.getCurrent()).setSize(bo.getSize());
        QueryWrapper<CuVolunteers> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().apply("cu_volunteers_service_count < cu_volunteers_count_recruiting").gt(CuVolunteers::getCuVolunteersEndDate, LocalDateTime.now());
        page = volunteersMapper.selectPage(page, queryWrapper);
        List<VolunteersDTO> volunteersDTOS = JSONObject.parseArray(JSONObject.toJSONString(page.getRecords()), VolunteersDTO.class);
        IPage<VolunteersDTO> result = new Page<>();
        BeanUtils.copyProperties(page, result);
        volunteersDTOS.forEach(l->{
            l.setCuVolunteersUrl(Consts.MyConsts.DetailsUrl+"volunteers/"+l.getCuVolunteersId()+"-");
            if (!l.getCuVolunteersStop().isAfter(LocalDateTime.now())){
                l.setCuVolunteersState(1);
            }
        });
        result.setRecords(volunteersDTOS);
        return result;
    }
    //endregion

    //region 志愿者服务详细查询
    @Override
    public QueryDetailsDTO queryDetails(VolunteersBasicBO bo) {
        CuVolunteers cuVolunteers = volunteersMapper.selectById(bo.getCuVolunteersId());
        if (cuVolunteers==null){
            throw new BizException("未找到相关信息");
        }
        QueryDetailsDTO dto = new QueryDetailsDTO();
        BeanUtils.copyProperties(cuVolunteers, dto);
        CuVolunteersCategory cuVolunteersCategory = volunteersCategoryMapper.selectById(dto.getCuVolunteersCategoryId());
        dto.setCuVenuesCategoryName(cuVolunteersCategory.getCuVolunteersCategoryName());
        return dto;
    }
    //endregion

    //region 注册成为志愿者
    @Override
    public void registerVolunteers(RegisterVolunteersBO bo) {
        QueryWrapper<CuVolunteersUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CuVolunteersUser::getCuUserId, bo.getCuUserId());
        Verification code = verificationService.getCode(bo.getCuVolunteersPhone());
        if (!code.getCuVerificationCode().equals(bo.getCuVerificationCode())) {
            throw new BizException("验证码过期或错误");
        }
        Integer integer = volunteersUserMapper.selectCount(queryWrapper);
        if (integer > 0) {
            throw new BizException("您已经是志愿者,请勿重复注册");
        }
        CuVolunteersUser volunteersUser = new CuVolunteersUser();
        BeanUtils.copyProperties(bo, volunteersUser);
        volunteersUserMapper.insert(volunteersUser);
        userMapper.updateIsVolunteers(bo.getCuUserId());
    }
    //endregion

    //region 参加志愿者活动
    @Override
    public void volunteersSign(VolunteersSignBO bo) {
        QueryWrapper<CuVolunteersSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CuVolunteersSign::getCuVolunteersId, bo.getCuVolunteersId()).eq(CuVolunteersSign::getCuUserId, bo.getCuUserId());
        Integer integer = signMapper.selectCount(queryWrapper);
        if (integer > 0) {
            throw new BizException("您已经预约,请耐心等待审核");
        }

        User user = userMapper.selectById(bo.getCuUserId());
        if (user.getCuUserIsVolunteer() != 1) {
            throw new BizException("您还不是志愿者,请先注册成为志愿者");
        }

        CuVolunteers cuVolunteers = volunteersMapper.selectById(bo.getCuVolunteersId());
        cuVolunteers.setCuVolunteersServiceCount(cuVolunteers.getCuVolunteersServiceCount() + 1);
        volunteersMapper.updateById(cuVolunteers);

        CuVolunteersSign sign = new CuVolunteersSign();
        sign.setCuUserId(bo.getCuUserId());
        sign.setCuVolunteersId(bo.getCuVolunteersId());
        sign.setCuVolunteersUserId(cuVolunteers.getCuVolunteersUserId());
        signMapper.insert(sign);


    }
    //endregion

    //region 志愿者人数
    @Override
    public int volunteersCount() {
        Integer integer = volunteersUserMapper.selectCount(null);
        return integer;
    }
    //endregion

    //region 查询志愿者参与记录
    @Override
    public List<VolunteersDTO> getRecord(GetRecordBO bo) {
        List<VolunteersDTO> list = volunteersMapper.getRecord(bo);
        return list;
    }
    //endregion
}
